/**
 * Script of the page 'tags'
 */
var PageTag = new (function() {
	var $this = this;
	var timeout;
	var textinput;
	var tagsDisplayed = [];
	
	var loading = false;
	var haveError = false;
	var ajax;
	
	/**
	 * Init
	 * Load status in localStorage
	 */
	this.init = function(e, data) {
		loadTags();
	}
	
	/**
	 * Search tags
	 */
	this.searchTag = function(tag) {
		
		if (ajax) {
			ajax.abort();
			ajax = null;
		}
		
		loading = true;
		haveError = false;
		
		clearListView();
		updateListView();
		ajax = $.ajax({
			url: MikuClip.URL.WEBSERVICE_TAGS,
			data: {tag: tag, login: MikuClip.options.login, password: MikuClip.options.password},
			success: function(data) {
				try {
					var tags = JSON.parse(data);
					saveTags();
					if (tags.error_type && tags.error_type == "connection") {
						DialogConnectMikubook.setError(tags.error);
						DialogConnectMikubook.show();
					}
					else {					
						tagsDisplayed = [];
						clearListView();
						
						for (var i = 0; i < tags.length; i++) {
							addToListView(tags[i]);
							tagsDisplayed.push(tags[i]);
						}
						loading = false;
						updateListView();
						saveTags();
					}
				}
				catch (e) {
					onError({statusText: 'parsing_error'});
				}
			},
			error: onError
		});
	}
	
	/**
	 * When the search is validated
	 */
	function onSearch(data) {
		$this.searchTag($(this).val());
	}
	
	/**
	 * Error occured (403, 404, ...) or parsing error
	 */	
	function onError(e) {
		loading = false;
		if (e.statusText != "abort") {
			haveError = true;
		}
		ajax = null;
		updateListView();
	}
	
	/**
	 * Click on the refresh button
	 */ 
	function onRefresh() {
		tagsDisplayed = [];
		$("#tag-offset").val('');
		$("#page-tag #listview .tag-item").remove();
		$this.searchTag($("#tag-search").val());
	}	
		
	
	/**
	 * When a tag is selected, init the video tag list
	 */
	function initTagList() {
		var tag = $(this).html();
		PageTagVideoList.reset();
		
		$("#page-tag-videolist #tag").val(tag);
		$("#page-tag-videolist #span-tag").html(tag);
		$("#page-tag-videolist #tag-offset").val('');
		$("#page-tag-videolist #tag-sort").val('newest');
		WebappHistory.push();
	}
	
	/**
	 * Save the current status of the page (video loading, videos displayed, offset)
	 */
	function saveTags() {
		window.localStorage['page_tag'] = JSON.stringify({
			'tag': $("#tag-search").val(),
			'listTags': tagsDisplayed,
			'loading': loading
		});
	}
	
	/**
	 * Load the saved status of the page
	 */
	function loadTags() {
		if (window.localStorage['page_tag']) {
			var o = JSON.parse(window.localStorage['page_tag']);
			$("#tag-search").val(o.tag);
			loading = o.loading;
			
			if (loading) {
				$this.searchTag(o.tag);
			}
			else {
				tagsDisplayed = [];
				clearListView();
				for (var i = 0; i < o.listTags.length; i++) {
					addToListView(o.listTags[i]);
					tagsDisplayed.push(o.listTags[i]);
				}
				
				updateListView();
			}
			
			$("#page-tag #listview").listview('refresh');
			
		}
	}
	
	/**
	 * Update the main listview (more element, loading, error, no videos)
	 */
	function updateListView() {
		if (loading) {
			$("#page-tag #listview-loader-top").css("display", "block");
		}
		else {
			$("#page-tag #listview-loader-top").css("display", "none");
		}
		
		if (!haveError && !loading && !tagsDisplayed.length && $("#tag-search").val()) {
			$("#page-tag #listview-item-notfound").css("display", "block");
		}
		else {
			$("#page-tag #listview-item-notfound").css("display", "none");
		}
		
		if (haveError) {
			$("#page-tag #listview-item-error").css("display", "block");
		}
		else {
			$("#page-tag #listview-item-error").css("display", "none");
		}
		
		refreshListView();
	}
	
	/**
	 * Clear the main list view
	 */	
	function clearListView() {
		$("#page-tag #listview .tag-item").remove();
		refreshListView();
	}
	
	/**
	 * Add an video to listview
	 */	
	function addToListView(tag) {
		$("#page-tag #listview").append('<li class="tag-item"><a href="#page-tag-videolist" data-transition="slide">'+tag+'</a></li>');
		refreshListView();
	}
	
	/**
	 * Refresh the JQuery Mobile Widget, if loaded
	 */
	function refreshListView() {
		try {
			$("#page-tag #listview").listview('refresh');
		} catch(e) {
		}
	}

	$("body").on("pagebeforeshow", "#page-tag", this.init);
	$("#page-tag").on("change", "#tag-search", onSearch);
	$("#page-tag").on("click", ".tag-item a", initTagList);
	$("#page-tag").on("click", "#btn-refresh", onRefresh);
});